package com.group2.operations.shiro;


import com.group2.operations.model.Admin;
import com.group2.operations.model.Permission;
import com.group2.operations.model.Role;
import com.group2.operations.service.AdminService;
import com.group2.operations.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class AdminRealm extends AuthorizingRealm{
    @Autowired
    private AdminService adminService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前的用户
        Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        //获取当前用户的角色
        Role role = admin.getRole();
        //添加角色
        info.addRole(role.getName());
        //添加权限
        for(Permission permission : role.getPermissions()) {
            info.addStringPermission(permission.getName());
        }
        //System.out.println(info);

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        Admin admin = adminService.queryUsernameByName(userToken.getUsername());
        if(admin == null) {
            return null;    //抛出异常
        }
        //取出盐并编码
        ByteSource salt = ByteSource.Util.bytes(MD5Utils.SALT);

        //密码认证由Shiro完成
        return new SimpleAuthenticationInfo(admin, admin.getPwd(), salt, getName());
    }
}
